package org.easy.tool.service.impl;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.easy.tool.common.DeepSeekUtil;
import org.easy.tool.entity.Question;
import org.easy.tool.mapper.QuestionMapper;
import org.easy.tool.service.IQuestion;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Valley
 * @since 2025-02-17 19:58:35
 */
@Service
public class QuestionService extends ServiceImpl<QuestionMapper, Question> implements IQuestion {

    @Autowired
    QuestionMapper questionMapper;

    @Override
    public String askAI(String question) {
        String answer = DeepSeekUtil.askAI(question);
        Question entity = new Question();
        entity.setQuestion(question);
        entity.setAsk(answer);
        this.save(entity);
        return answer;
    }

    @Override
    public SseEmitter sseEmit(String message) {
        SseEmitter emitter = new SseEmitter(60000L); // 超时时间60秒

        // 异步处理流式逻辑（避免阻塞主线程）
        CompletableFuture.runAsync(() -> {
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpPost httpPost = DeepSeekUtil.buildPost(message);
                // 发送流式请求到第三方服务（如华为云）
                try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        // 解析第三方服务的流式响应
                        String chunk = parseChunk(line);
                        // 将数据块发送到前端
                        emitter.send(SseEmitter.event().data(chunk));
                    }
                    emitter.complete(); // 流结束时完成
                }
            } catch (Exception e) {
                emitter.completeWithError(e); // 异常处理
            }
        });
        return emitter;
    }

    @Override
    public boolean saveRecord(LinkedHashMap data) {
        String question = (String) data.get("question");
        String ask = (String) data.get("ask");
        Question entity = new Question();
        entity.setQuestion(question);
        entity.setAsk(ask);
        this.save(entity);
        return true;
    }

    private String parseChunk(String line) {
        // 示例：解析第三方服务的流式响应数据
        if (line.startsWith("data: ")) {
            return line.substring(6).trim(); // 提取有效内容
        }
        return "";
    }
}
